//
//  OffLineManagerViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14-8-28.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "OffLineManagerViewController.h"

@interface OffLineManagerViewController ()

@end

@implementation OffLineManagerViewController{
    /**
     *  底部菜单
     */
    BottomView *bottomView;
    /**
     *  列表视图
     */
    UITableView *managerTableView;
    /**
     *  删除列表
     */
    NSMutableArray *deleteArray;
    /**
     *  序列集
     */
    NSMutableIndexSet *indexSet;
    BOOL selectAllFlag;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                 [UIColor colorWithRed:255/255.0f green:159/255.f blue:0/255.f alpha:1], NSForegroundColorAttributeName,
                                                 nil] forState:UIControlStateSelected];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"离线观看";
    //创建视图
    [self creatView];
    //初始化数组
    deleteArray = [[NSMutableArray alloc]init];
    indexSet = [[NSMutableIndexSet alloc]init];
}
/**
 *  创建视图
 */
-(void)creatView{
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    //适配位置
    int h;
    if (isPad) {
        h =49;
    }else{
        h =49;
    }
    //导航栏
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(backToOffline)];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightBtn;
    //模拟  选择框
    int segh= 0;
    if (isPad) {
        segh = 40;
    }else{
        segh = 30;
    }
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[@"已完成",@"下载中"]];
    segment.selectedSegmentIndex = self.segIndex;
    segment.frame = RECT(SCREEN_WIDTH/5, 10, SCREEN_WIDTH*3/5, segh);
    segment.tintColor = [UIColor orangeColor];
    [self.view addSubview:segment];
    //列表
    managerTableView = [[UITableView alloc]initWithFrame:RECT(0, segh+10+10, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    managerTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    managerTableView.delegate = self;
    managerTableView.dataSource = self;
    managerTableView.contentOffset = self.point;
    [self.view addSubview:managerTableView];
    //一段时间之后可以编辑，这样才会有动画
    [self performSelector:@selector(setTableEdit) withObject:nil afterDelay:0.4];
    //底部
    bottomView = [[BottomView alloc]init];
    bottomView.frame = RECT(0, SCREEN_HEIGHT-h-64, SCREEN_WIDTH, h);
    bottomView.noteView.backgroundColor = [UIColor redColor];
if (isPad) {
        //
        bottomView.leftBtn.frame = RECT(-SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 49);
        bottomView.rightBtn.frame = RECT(SCREEN_WIDTH, 0, SCREEN_WIDTH/2, 49);
        bottomView.lineHorizontal.frame = RECT(SCREEN_WIDTH/2, 0, 0, 0);
        bottomView.lineVertical.frame = RECT(SCREEN_WIDTH/2, 3, 0, 0);
    }else{
        bottomView.leftBtn.frame = RECT(-SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 49);
        bottomView.rightBtn.frame = RECT(SCREEN_WIDTH, 0, SCREEN_WIDTH/2, 49);
        bottomView.lineHorizontal.frame = RECT(SCREEN_WIDTH/2, 0, 0, 0);
        bottomView.lineVertical.frame = RECT(SCREEN_WIDTH/2, 3, 0, 0);
    }
    [bottomView.rightBtn setTitle:@"删除" forState:UIControlStateNormal];
    [bottomView.rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bottomView.rightBtn addTarget:self action:@selector(returnDeleteArrayAndReturn) forControlEvents:UIControlEventTouchUpInside];
    [bottomView.leftBtn setTitle:@"全选" forState:UIControlStateNormal];
    [bottomView.leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bottomView.leftBtn addTarget:self action:@selector(selectAllVideos) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomView];
    //底部出现动画
    [bottomView showAnimationWithTime:0.8 andDely:0];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.8];
    managerTableView.frame = RECT(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49);
    [UIView commitAnimations];
}

#pragma mark - tableviewdelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.segIndex == 0) {
        return self.listArray.count;
    }else{
        return 1;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.segIndex == 0) {
        NSDictionary *dic = [self.listArray objectAtIndex:section];
        NSArray *array = [dic objectForKey:@"array"];
        return array.count;
    }else{
        return self.listArray.count;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.segIndex == 0) {
        return 60.0f;
    }else{
        return 0;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.segIndex == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
        //            view.backgroundColor = [UIColor colorWithRed:1 green:0.5 blue:0 alpha:0.5];
        view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
        
        NSDictionary *dic = [self.listArray objectAtIndex:section];
        NSString *string = [dic objectForKey:@"name"];
        NSArray *array = [string componentsSeparatedByString:@" "];
        
        UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 2)];
        line.backgroundColor = [UIColor orangeColor];
        
        UILabel *label1 = [[UILabel alloc]initWithFrame:RECT(0, 4, SCREEN_WIDTH, 20)];
        label1.numberOfLines = 0;
        label1.font = FONT_SYS_LITTLE;
        label1.textColor = [UIColor darkGrayColor];
        label1.backgroundColor = [UIColor clearColor];
        label1.textAlignment = NSTextAlignmentCenter;
        label1.text = [array objectAtIndex:0];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:RECT(30, 0, SCREEN_WIDTH-20, 45)];
        label2.numberOfLines = 0;
        label2.textColor = [UIColor blackColor];
        label2.font = FONT_SYS_NORMAL;
        label2.backgroundColor = [UIColor clearColor];
        //            label2.textAlignment = NSTextAlignmentCenter;
        label2.text = string;
        
        if (array.count>=3) {
            //
            UILabel *label3 = [[UILabel alloc]initWithFrame:RECT(0, 40, SCREEN_WIDTH, 20)];
            label3.numberOfLines = 0;
            label3.textColor = GreenColor;
            label3.text = [array lastObject];
            label3.backgroundColor = [UIColor clearColor];
            label3.textAlignment = NSTextAlignmentRight;
            //                [view addSubview:label3];
        }
        
        UILabel *teacherLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 40, SCREEN_WIDTH-20, 15)];
        teacherLabel.text = @"主讲老师:";
        teacherLabel.font = FONT_SYS_LITTLE;
        teacherLabel.textColor = [UIColor darkGrayColor];
        UILabel *teacher = [[UILabel alloc]initWithFrame:CGRectMake(95, 40, SCREEN_WIDTH/2, 15)];
//        logdebug(@"%@",dic);
        NSArray *ar = [dic objectForKey:@"array"];
        NSDictionary *d = [ar firstObject];
        NSString *te = [d objectForKey:@"videoTeacher"];
        teacher.text = te;
        teacher.font = FONT_SYS_LITTLE;
        teacher.textColor = [UIColor orangeColor];
        
        UILabel *lecLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2+30, 40, 40, 15)];
        lecLabel.text= @"课时:";
        lecLabel.font = FONT_SYS_LITTLE;
        lecLabel.textColor = [UIColor darkGrayColor];
        UILabel *lec = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2+30+35, 40, 50, 15)];
        lec.text = [d objectForKey:@"videoLectureNum"];
        lec.textColor = [UIColor orangeColor];
        lec.font = FONT_SYS_LITTLE;
        
        //            [view addSubview:label1];
        //            [view addSubview:line];
        [view addSubview:label2];
        [view addSubview:teacherLabel];
        [view addSubview:teacher];
        [view addSubview:lecLabel];
        [view addSubview:lec];
        
        return view;
    }else{
        return nil;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segIndex == 0) {
        return 80;
    }else{
        return 90;
    }
}
//多选模式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segIndex == 0) {
        //下载完成的，需要分组
        OffLineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"downloadedcell"];
        if (cell == nil) {
            cell = [[OffLineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downloadedcell" tag:0];
        }
        cell.point.hidden = YES;
        cell.line.hidden = YES;
        //赋值
        if (self.listArray.count>0) {
            NSDictionary *dic = [self.listArray objectAtIndex:indexPath.section];
            NSArray *dicArray = [dic objectForKey:@"array"];
            NSDictionary *itemDic = [dicArray objectAtIndex:indexPath.row];
            cell.titleLabel.text = [itemDic objectForKey:@"videoSection"];
            cell.chapterLabel.text = [itemDic objectForKey:@"videoChapter"];
            cell.teacherLabel.text = [itemDic objectForKey:@"videoTeacher"];
            cell.durationLabel.text = [NSString stringWithFormat:@"%@分",[itemDic objectForKey:@"videoDuration"]];
        }
        return cell;
    }else{
        //下载中
        OffLineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"downloadingcell"];
        if (cell == nil) {
            cell = [[OffLineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downloadingcell" tag:1];
        }
        if (self.listArray.count>0) {
            DownloadItem *item = [self.listArray objectAtIndex:indexPath.row];
            cell.titleLabel.text = item.videoSection;
            cell.lectureLabel.text = item.videoTitle;
            cell.teacherLabel.text = item.videoTeacher;
            cell.durationLabel.text = [NSString stringWithFormat:@"%ld分",(long)item.videoDuration];
            cell.progress.hidden = YES;
        }
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segIndex == 0) {
        //
        [deleteArray addObject:indexPath];
    }else{
        [deleteArray addObject:indexPath];
        [indexSet addIndex:indexPath.row];
    }
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segIndex == 0) {
        //
        [deleteArray removeObject:indexPath];
    } else {
        [deleteArray removeObject:indexPath];
        [indexSet removeIndex:indexPath.row];
    }
    
}
/**
 *  取消按钮的返回
 */
-(void)backToOffline{
    [self.navigationController popViewControllerAnimated:NO];
}
/**
 *  可编辑
 */
-(void)setTableEdit{
    [managerTableView setEditing:YES animated:YES];
}
/**
 *  全选
 */
-(void)selectAllVideos{
    if (self.segIndex == 0) {
        //已完成的全选
        logdebug(@"全选--完成");
        if (selectAllFlag) {
            selectAllFlag = NO;
            [deleteArray removeAllObjects];
            //取消选择
            for (int i = 0; i<self.listArray.count; i++) {
                NSDictionary *dic = [self.listArray objectAtIndex:i];
                NSArray *array = [dic objectForKey:@"array"];
                for (int j = 0; j<array.count; j++) {
                    [managerTableView deselectRowAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i] animated:YES];
                }
            }
            [bottomView.leftBtn setTitle:@"全选" forState:UIControlStateNormal];
            [bottomView.leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }else{
            selectAllFlag = YES;
            for (int i = 0; i<self.listArray.count; i++) {
                NSDictionary *dic = [self.listArray objectAtIndex:i];
                logdebug(@"%@",dic);
                NSArray *array = [dic objectForKey:@"array"];
                for (int j = 0; j < array.count; j++) {
                    NSIndexPath *index = [NSIndexPath indexPathForItem:j inSection:i];
                    [managerTableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionNone];
                    [deleteArray addObject:index];
                }
            }
            [bottomView.leftBtn setTitle:@"取消全选" forState:UIControlStateNormal];
            [bottomView.leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }else{
        if (selectAllFlag) {
            selectAllFlag = NO;
            
            for (int i = 0; i<self.listArray.count; i++) {
                [managerTableView deselectRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0] animated:YES];
            }
            [deleteArray removeAllObjects];
            [bottomView.leftBtn setTitle:@"全选" forState:UIControlStateNormal];
        }else{
            selectAllFlag = YES;
            for (int i = 0; i<self.listArray.count; i++) {
                NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
                [deleteArray addObject:index];
            }
            logdebug(@"%@",deleteArray);
            for (int i = 0; i<self.listArray.count; i++) {
                [managerTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
            }
            [bottomView.leftBtn setTitle:@"取消全选" forState:UIControlStateNormal];
        }
    }
    
}
/**
 *  返回删除数组
 */
-(void)returnDeleteArrayAndReturn{
    if (self.segIndex == 0) {
        for (NSIndexPath *indexPath in deleteArray) {
            if (![indexSet containsIndex:indexPath.section]) {
                [indexSet addIndex:indexPath.section];
            }
        }
    }else{
        for (NSIndexPath *indexPath in deleteArray) {
            if (![indexSet containsIndex:indexPath.row]) {
                [indexSet addIndex:indexPath.row];
            }
        }
    }
    self.deleteBlock(indexSet,deleteArray);
    [self.navigationController popViewControllerAnimated:NO];
}
//----------------------------
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
